import { $ } from "./utils"
import { fetchJson } from "./fetch";

const render = Symbol("render");
const event = Symbol("event");
class Region {

    constructor(opts) {
        if (!opts.container) {
            throw "请填写container配置"
        }
        if (!opts.name) {
            throw "请填写name配置"
        }
        this[render](opts);
        this[event](opts);
    }

    [render](opts) {

        const tpl = `<div>
            <select id="region-province-select"></select>
            <select id="region-city-select"></select>
            <select id="region-area-select"></select>
            <input id="region-selected"  type="hidden" name="${opts.name}" valid="${opts.present ? 'present': ''}"/>
        </div>`;
        opts.container.innerHTML= tpl;

    }
    async [event](opts){

        let regionData = await fetchJson("/region-data",{});
        regionData = regionData.data;

        const $provinceSelect = $("region-province-select");
        const $citySelect = $("region-city-select");
        const $areaSelect = $("region-area-select");
        const $result = $("region-selected");

        let provinceSelected;
        let citySelected;
        let areaSelected;
        let provinceOptions = `<option></option>`;
        for (let item of regionData) {
            provinceOptions += `<option value="${ item.id}">${item.name}</option>`;
        }
        $provinceSelect.innerHTML = provinceOptions;

        const provinceChange = ()=> {
            const i = parseInt($provinceSelect.value);
            provinceSelected = i;
            const citys = regionData[i-1].city;
            let cityOptions = "";
            for (let item of citys) {
                cityOptions += `<option value="${ item.id }">${item.name}</option>`;
            }
            $citySelect.innerHTML = cityOptions;

        };
        const cityChange = ()=> {
            citySelected = parseInt($citySelect.value);
            const areas = regionData[provinceSelected-1].city.filter((item) => {
                return item.id === citySelected
            })[0].district;

            let areaOptions = "";
            for (let item of areas) {
                areaOptions += `<option value="${ item.id}">${item.name}</option>`;
            }
            $areaSelect.innerHTML = areaOptions;
        };
        const areaChange = ()=> {
            areaSelected = parseInt($areaSelect.value);
            $result.value = provinceSelected + "," + citySelected + "," + areaSelected;
        };

        //绑定事件
        $provinceSelect.onchange = (e) => {
            provinceChange();
            cityChange();
            areaChange();
        };

        $citySelect.onchange = (e) => {
            cityChange();
            areaChange();
        };
        $areaSelect.onchange = (e) => {
            areaChange();
        };

    }

}
export default Region;